/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.bizon.dinner.gui.topcompoments;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Logger;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import org.bizon.dinner.gui.dialogs.SecuritySystem;
import org.netbeans.TopSecurityManager;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

import diiner.common.webaccess.UnAutorizationException_Exception;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.bizon.dinner.gui.topcompoments//dinner//EN", autostore = false)
public final class DinnerTopComponent extends TopComponent {

	private static DinnerTopComponent instance;
	/** path to the icon used by the component and its open action */
	// static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
	private static final String PREFERRED_ID = "dinnerTopComponent";

	/**
	 * Obtain the DinnerTopComponent instance. Never call {@link #getDefault}
	 * directly!
	 */
	public static synchronized DinnerTopComponent findInstance() {
		TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
		if (win == null) {
			Logger.getLogger(DinnerTopComponent.class.getName()).warning(
					"Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
			return getDefault();
		}
		if (win instanceof DinnerTopComponent)
			return (DinnerTopComponent) win;
		Logger.getLogger(DinnerTopComponent.class.getName()).warning(
				"There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
		return getDefault();
	}

	/**
	 * Gets default instance. Do not use directly: reserved for *.settings files
	 * only, i.e. deserialization routines; otherwise you could get a
	 * non-deserialized instance. To obtain the singleton instance, use
	 * {@link #findInstance}.
	 */
	public static synchronized DinnerTopComponent getDefault() {
		if (instance == null) {
			instance = new DinnerTopComponent();
		}
		return instance;
	}

	private DinnerTableModel tableModel = null;


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton cacnelButton;
    private JLabel jLabel1;
    private JScrollPane jScrollPane1;
    private JTable jTable1;
    private JTextField jTextField1;
    private JButton okButton;
    private JButton reloadButton;
    // End of variables declaration//GEN-END:variables

	public DinnerTopComponent() {
		initsec();
		initComponents();
		setName(NbBundle.getMessage(DinnerTopComponent.class, "CTL_dinnerTopComponent"));
		setToolTipText(NbBundle.getMessage(DinnerTopComponent.class, "HINT_dinnerTopComponent"));
		// setIcon(ImageUtilities.loadImage(ICON_PATH, true));
		putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
		putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
		putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
		putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
		jTable1.getModel().addTableModelListener(new TableModelListener() {
			@Override
			public void tableChanged(TableModelEvent e) {
				calculate();
			}
		});
                calculate();
	}

         private void calculate() {
                String summ = String.format("%f", tableModel.countSumm());
                jTextField1.setText(summ.substring(0, summ.length() - 2));
            }

	@Override
	public void componentClosed() {
		SecuritySystem.logout();
	}

	@Override
	public void componentOpened() {

	}

	@Override
	public int getPersistenceType() {
		return TopComponent.PERSISTENCE_NEVER;
	}

	@Override
	protected String preferredID() {
		return PREFERRED_ID;
	}

	private void cacnelButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_cacnelButtonActionPerformed
		TopSecurityManager.exit(0);
	}// GEN-LAST:event_cacnelButtonActionPerformed

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new JScrollPane();
        jTable1 = new JTable();
        cacnelButton = new JButton();
        okButton = new JButton();
        reloadButton = new JButton();
        jTextField1 = new JTextField();
        jLabel1 = new JLabel();

        jTable1.setModel(getDinnerTableModel());
        jScrollPane1.setViewportView(jTable1);



        cacnelButton.setText(NbBundle.getMessage(DinnerTopComponent.class, "DinnerTopComponent.cacnelButton.text")); // NOI18N
        cacnelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                cacnelButtonActionPerformed(evt);
            }
        });

        okButton.setText(NbBundle.getMessage(DinnerTopComponent.class, "DinnerTopComponent.okButton.text")); // NOI18N
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        reloadButton.setText(NbBundle.getMessage(DinnerTopComponent.class, "DinnerTopComponent.reloadButton.text")); // NOI18N
        reloadButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                reloadButtonActionPerformed(evt);
            }
        });

        jTextField1.setHorizontalAlignment(JTextField.TRAILING);
        jTextField1.setText(NbBundle.getMessage(DinnerTopComponent.class, "DinnerTopComponent.jTextField1.text")); // NOI18N
        jLabel1.setText(NbBundle.getMessage(DinnerTopComponent.class, "DinnerTopComponent.jLabel1.text")); // NOI18N
        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(Alignment.TRAILING)
                    .addComponent(jScrollPane1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, 67, GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(reloadButton)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(okButton)
                        .addPreferredGap(ComponentPlacement.RELATED)
                        .addComponent(cacnelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(Alignment.LEADING)
            .addGroup(Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 418, Short.MAX_VALUE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                    .addComponent(cacnelButton)
                    .addComponent(okButton)
                    .addComponent(reloadButton)
                    .addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

        private void reloadButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_reloadButtonActionPerformed
        try {
            SecuritySystem.getDinnerService().clearData(SecuritySystem.getID());
           getDinnerTableModel().setNewList(SecuritySystem.getDinnerService().getList(SecuritySystem.getID()));
           calculate();
        } catch (UnAutorizationException_Exception ex) {
            Exceptions.printStackTrace(ex);
        }
        }//GEN-LAST:event_reloadButtonActionPerformed

	private void initsec() {
		SecuritySystem.login();
	}

	private void okButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_okButtonActionPerformed
		try {
			SecuritySystem.getDinnerService().setList(getDinnerTableModel().getEats(), SecuritySystem.getID());
		} catch (UnAutorizationException_Exception e) {
			e.printStackTrace();
			SecuritySystem.showError(e);
		}
		TopSecurityManager.exit(0);
	}// GEN-LAST:event_okButtonActionPerformed

	private void readPropertiesImpl(java.util.Properties p) {
		// String version = p.getProperty("version");
		// TODO read your settings according to their version
	}

	DinnerTableModel getDinnerTableModel() {
		if (tableModel == null) {
			tableModel = new DinnerTableModel(DinnerController.getInstance().loadEat());
		}
		return tableModel;
	}

	Object readProperties(java.util.Properties p) {
		if (instance == null) {
			instance = this;
		}
		instance.readPropertiesImpl(p);
		return instance;
	}

	void writeProperties(java.util.Properties p) {
		// better to version settings since initial version as advocated at
		// http://wiki.apidesign.org/wiki/PropertyFiles
		p.setProperty("version", "1.0");
		// TODO store your settings
	}
}
